import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Catalog {
	private static String CATALOG = "catalog.txt";
	private ArrayList<FlowerClip> clips;

	public Catalog() {
		clips = new ArrayList<FlowerClip>();
	}

	private void loadCatalog() throws IOException {

		File file = new File(CATALOG);
		String[] splitVals = null;
		String splitter = "";

		if (!file.isFile() && !file.createNewFile()) {
			throw new IOException("Error creating new file: "
					+ file.getAbsolutePath());
		}

		BufferedReader r = new BufferedReader(new FileReader(file));
		try {
			while ((splitter = r.readLine()) != null) {
				splitVals = splitter.split(":");
				loadClip(splitVals);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			r.close();
		}

	}

	public void saveCatalog() throws IOException {
		StringBuilder sb = new StringBuilder();
		for (FlowerClip f : this.clips) {
			sb.append(f.getName());
			sb.append(":");
			sb.append(f.getPrice());
			sb.append(":");
			sb.append(f.getDescription());
		}

		File file = new File(CATALOG);
		FileWriter writer;
		try {
			writer = new FileWriter(file, true);
			BufferedWriter out = new BufferedWriter(writer);
			out.write(sb.toString());
			out.newLine();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addClip(FlowerClip e) {
		if (!clips.contains(e)) {
			clips.add(e);
		}
	}

	private void loadClip(String[] info) {

		double price = 0;
		for (int i = 0; i < info[1].length(); i++) {
			if (info[1].charAt(i) == '.') {
				price = price / 10;
			} else {
				price = price * 10;
				price = price + Integer.parseInt(info[1].charAt(i) + "");
			}
		}

		FlowerClip fc = new FlowerClip(info[0], price, info[2]);
		clips.add(fc);

	}

	public void deleteClip(FlowerClip c) {
		clips.remove(c);
	}

	public static void main(String[] arg) {
		Catalog c = new Catalog();
		/*
		 * c.addClip(new FlowerClip("sum",12,"idk")); try { c.saveCatalog(); }
		 * catch (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */

		try {
			c.loadCatalog();
			System.out.print(c.clips);
		} catch (IOException e) {

			e.printStackTrace();
		}

	}
}
